/**
 * system send email
 */
package utils

import (
	"MPCBot/model"
	"fmt"
	"log"
	"strconv"
	"strings"
	"time"

	"gopkg.in/gomail.v2"
)

func SendMail(mailTo []string, subject string, body string) error {

	mailConn := map[string]string{
		"user": "ghm20221212@163.com",
		"pass": "GAHEBKONUEDIIPXO",
		"host": "smtp.163.com",
		"port": "465",
	}

	port, _ := strconv.Atoi(mailConn["port"]) //转换端口类型为int

	m := gomail.NewMessage()

	m.SetHeader("From", m.FormatAddress(mailConn["user"], "hermit"))
	m.SetHeader("To", mailTo...)    //send multiple email
	m.SetHeader("Subject", subject) //Set message subject
	m.SetBody("text/html", body)    //Set message context

	d := gomail.NewDialer(mailConn["host"], port, mailConn["user"], mailConn["pass"])
	err := d.DialAndSend(m)
	return err

}

// email notice
func SendNotice(noticeInfo string, title string) {
	// send email to admin
	mailTo := []string{
		"13321139330@163.com",
		"2774738269@qq.com",
		"pthn8181@gmail.com",
		"2659840502@qq.com",
		"18447125326@163.com",
	}
	//email subject
	subject := time.Now().Format("2006-01-02") + title
	body := noticeInfo
	if strings.Contains(body, "record") || strings.Contains(body, "redigo") {
		return
	}
	errr := SendMail(mailTo, subject, body)
	if errr != nil {
		log.Println(errr)
		fmt.Println(model.Red, "report send fail", model.Reset)
		return
	}

	fmt.Println(model.Red, "Notice email send successfully", model.Reset)
}

// email notice
func SendError(err error) {
	// send email to admin
	mailTo := []string{
		"13321139330@163.com",
	}
	//email subject
	subject := time.Now().Format("2006-01-02") + "Error report"
	body := fmt.Sprintf("%v", err)
	errr := SendMail(mailTo, subject, body)
	if errr != nil {
		log.Println(errr)
		fmt.Println(" report send fail")
		return
	}

	fmt.Println("error report send successfully")
}
